<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import { useIndicatorStore } from "@/stores/indicator"
import { useTopSelectStore } from "@/stores/topSelect"

const indicatorStore = useIndicatorStore()
const topSelectStore = useTopSelectStore()

// 响应式数据
const indicators = computed(() => indicatorStore.getIndicatorList);
const selectedYear = computed(() => String(topSelectStore.getTime));

// 生成历年数据 (2018-2023)
const generateYearData = () => {
  const years = ['2018', '2019', '2020', '2021', '2022', '2023'];
  const data: { [key: string]: { [key: string]: number } } = {};
  
  // 为每个指标设置基础分数和增长趋势
  const indicatorTrends = {
    '健康舒适': { base: 75, trend: 'up', volatility: 2 },
    '交通便捷': { base: 100, trend: 'up', volatility: 3 },
    '环境宜居': { base: 82, trend: 'stable', volatility: 1 },
    '社会和谐': { base: 91, trend: 'up', volatility: 1.5 },
    '文化繁荣': { base: 73, trend: 'up', volatility: 2.5 },
    '管理有序': { base: 79, trend: 'stable', volatility: 1.5 }
  };
  
  indicators.value.forEach(indicator => {
    data[indicator.name] = {};
    const trend = indicatorTrends[indicator.name as keyof typeof indicatorTrends];
    
    if (trend) {
      years.forEach((year, index) => {
        let score = trend.base;
        
        // 根据趋势类型调整分数
        if (trend.trend === 'up') {
          score += index * 1.5; // 逐年上升
        } else if (trend.trend === 'stable') {
          score += index * 0.8; // 稳定增长
        }
        
        // 添加随机波动
        const randomVariation = (Math.random() - 0.5) * trend.volatility;
        score += randomVariation;
        
        // 确保分数在合理范围内 (70-95)
        score = Math.max(70, Math.min(95, Math.round(score)));
        
        data[indicator.name][year] = score;
      });
    }
  });
  
  return data;
};

const yearData = ref(generateYearData());

// 获取当前年份的指标数据
const getCurrentYearData = () => {
  const currentYear = selectedYear.value;
  
  // 为每个指标设置不同的默认值
  const defaultValues: { [key: string]: number } = {
    '健康舒适': 75,
    '交通便捷': 90,
    '环境宜居': 82,
    '社会和谐': 91,
    '文化繁荣': 73,
    '管理有序': 79
  };
  
  return indicators.value.map(indicator => ({
    name: indicator.name,
    value: yearData.value[indicator.name]?.[currentYear] || defaultValues[indicator.name] || 90,
    color: getIndicatorColor(indicator.name)
  }));
};

// 为不同指标分配颜色
const getIndicatorColor = (indicatorName: string) => {
  const colorMap: { [key: string]: string } = {
    '健康舒适': '#4fc3f7',
    '交通便捷': '#ffb300',
    '环境宜居': '#4caf50',
    '社会和谐': '#ff5722',
    '文化繁荣': '#9c27b0',
    '管理有序': '#00bcd4'
  };
  return colorMap[indicatorName] || '#607d8b';
};

const indicatorData = ref(getCurrentYearData());

const option = ref({
  tooltip: {
    trigger: 'axis',
    backgroundColor: "rgba(0,0,0,.6)",
    borderColor: "rgba(147, 235, 248, .8)",
    textStyle: { color: "#FFF" },
    formatter: function(params: any) {
      return `${params[0].name}<br/>${params[0].seriesName}: ${params[0].value}分`;
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: indicatorData.value.map(item => item.name),
    axisLine: {
      lineStyle: { color: '#fff' }
    },
    axisLabel: {
      color: '#fff',
      fontSize: 12,
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    min: 60,
    max: 100,
    axisLine: {
      lineStyle: { color: '#fff' }
    },
    axisLabel: {
      color: '#fff',
      fontSize: 12
    },
    splitLine: {
      lineStyle: { color: 'rgba(255,255,255,0.1)' }
    }
  },
  series: [{
    name: '指标得分',
    type: 'bar',
    data: indicatorData.value.map(item => ({
      value: item.value,
      itemStyle: {
        color: item.color
      }
    })),
    barWidth: '60%',
    label: {
      show: true,
      position: 'top',
      color: '#fff',
      fontSize: 12
    }
  }]
});

// 图表点击事件处理
const handleChartClick = (params: any) => {
  if (params.componentType === 'series') {
    // 点击柱状图数据
    const indicatorName = indicatorData.value[params.dataIndex]?.name;
    if (indicatorName) {
      console.log('选中指标:', indicatorName);
      // 这里可以添加指标选择的逻辑
    }
  }
};

// 更新图表配置
const updateOption = () => {
  indicatorData.value = getCurrentYearData();
  
  // 只更新变化的数据部分
  option.value.xAxis.data = indicatorData.value.map(item => item.name);
  option.value.series[0].data = indicatorData.value.map(item => ({
    value: item.value,
    itemStyle: {
      color: item.color
    }
  }));
};

watch([topSelectStore, indicatorStore], () => {
  // 当选择变化时更新图表
  updateOption();
}, {
  deep: true,
  immediate: true
});

const initData = () => {
  updateOption();
}

onMounted(() => {
  initData()
})
</script>

<template>
  <div class="trend-chart">
    <v-chart 
      :option="option" 
      autoresize 
      @click="handleChartClick"
    />
  </div>
</template>

<style scoped lang="scss">
.trend-chart {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}
</style>
